<?php
namespace Admin\Controller;
use Think\Controller;

class GoodsController extends HomeController {
    
    public function _initialize(){
        $storeList = D('Stores')->getStoresAllList();
        $this->assign('storeList',$storeList);
    }
	/*
	* Function:		goodsList
	* Description:	商品列表
	*/
    public function goodsList(){
		$filter = I('param.');
		$page =  I('get.p',1);
		$pageSize = 10;
		$filter['is_show'] = 1;
		$filter['type'] = 3;
		$filter = returnFilter($filter);
		$list = D('Goods')->getGoodsList($page,$filter,$pageSize);
		if(is_array($list)&&count($list)>0){
		    foreach($list as &$val){
		        $val['cate_name'] = M('goods_cate')->where(['id'=>$val['cate_id']])->getField('cate_name');
		        $val['goods_stock'] = M('goods_list')->where(['goods_id'=>$val['id'],'status'=>1,'is_deleted'=>0])->sum('stocks-freez');
                $val['is_recommend'] = ($val['is_recommend']==1)?'是':'否';
		    }
		}
		$count =  D('Goods')->getGoodsCount($filter);
		$pages = getpage($count,$pageSize,$filter);
		$show = $pages->show();
		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->assign('filter',$filter);
        $goodsCateList = D('GoodsCate')->getGoodsCateAllList(0);
        if(is_array($goodsCateList)&&count($goodsCateList)>0){
            foreach($goodsCateList as &$val){
                $val['second_list'] = M('goods_cate')->where(['pid'=>$val['id'],'status'=>1,'is_deleted'=>0])->order('sort desc,id desc')->select();
            }
        }
        $this->assign('goodsCateList',$goodsCateList);
        $recommendList = [['id'=>0,'name'=>'否'],['id'=>1,'name'=>'是']];
        $this->assign('recommendList',$recommendList);
		$this->display();
    }
    
    /*
	* Function:		cardList
	* Description:	会员卡列表
	*/
    public function cardList(){
		$filter = I('param.');
		$page =  I('get.p',1);
		$pageSize = 10;
		$filter['is_show'] = 1;
		$filter['type'] = 2;
		$filter = returnFilter($filter);
		$list = D('Goods')->getGoodsList($page,$filter,$pageSize);
		if(is_array($list)&&count($list)>0){
		    foreach($list as &$val){
		        $val['cate_name'] = M('goods_cate')->where(['id'=>$val['cate_id']])->getField('cate_name');
		        $val['goods_stock'] = M('goods_list')->where(['goods_id'=>$val['id'],'status'=>1,'is_deleted'=>0])->sum('stocks-freez');
                $val['is_recommend'] = ($val['is_recommend']==1)?'是':'否';
		    }
		}
		$count =  D('Goods')->getGoodsCount($filter);
		$pages = getpage($count,$pageSize,$filter);
		$show = $pages->show();
		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->assign('filter',$filter);
        $goodsCateList = D('GoodsCate')->getGoodsCateAllList(0);
        if(is_array($goodsCateList)&&count($goodsCateList)>0){
            foreach($goodsCateList as &$val){
                $val['second_list'] = M('goods_cate')->where(['pid'=>$val['id'],'status'=>1,'is_deleted'=>0])->order('sort desc,id desc')->select();
            }
        }
        $this->assign('goodsCateList',$goodsCateList);
        $recommendList = [['id'=>0,'name'=>'否'],['id'=>1,'name'=>'是']];
        $this->assign('recommendList',$recommendList);
		$this->display();
    }
    
    /*
	* Function:		videoList
	* Description:	视频列表
	*/
    public function videoList(){
		$filter = I('param.');
		$page =  I('get.p',1);
		$pageSize = 10;
		$filter['is_show'] = 1;
		$filter['type'] = 1;
		$filter = returnFilter($filter);
		$list = D('Goods')->getGoodsList($page,$filter,$pageSize);
		if(is_array($list)&&count($list)>0){
		    foreach($list as &$val){
		        $val['cate_name'] = M('goods_cate')->where(['id'=>$val['cate_id']])->getField('cate_name');
		        $val['goods_stock'] = M('goods_list')->where(['goods_id'=>$val['id'],'status'=>1,'is_deleted'=>0])->sum('stocks-freez');
                $val['is_recommend'] = ($val['is_recommend']==1)?'是':'否';
		    }
		}
		$count =  D('Goods')->getGoodsCount($filter);
		$pages = getpage($count,$pageSize,$filter);
		$show = $pages->show();
		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->assign('filter',$filter);
        $goodsCateList = D('GoodsCate')->getGoodsCateAllList(0);
        if(is_array($goodsCateList)&&count($goodsCateList)>0){
            foreach($goodsCateList as &$val){
                $val['second_list'] = M('goods_cate')->where(['pid'=>$val['id'],'status'=>1,'is_deleted'=>0])->order('sort desc,id desc')->select();
            }
        }
        $this->assign('goodsCateList',$goodsCateList);
        $recommendList = [['id'=>0,'name'=>'否'],['id'=>1,'name'=>'是']];
        $this->assign('recommendList',$recommendList);
		$this->display();
    }
    
    /*
	* Function:		addGoods
	* Description:	添加商品
	*/
	public function addGoods(){
		$ret = array();
		if(IS_POST){
			$data = I('post.');
			if(empty($data['sort'])){
			    $data['sort'] = 0;
			}
			if(is_array($data['smallimage'])&&count($data['smallimage'])>0){
			    $data['goods_small_pic'] = $data['smallimage'][0];
			    $data['goods_image'] = implode(',',$data['smallimage']);
			}
			unset($data['smallimage']);
            $goodsPrice = [];//多规格商品价格数组
			if(is_array($data['skus'])&&count($data['skus'])>0){//多规格
                $itemData = [];
                $data['is_more_spec'] = 1;
                foreach($data['skus'] as $key=>$val){
                    $val['goods_spec_id'] = $key;
                    $specData = explode('-',$key);
                    if(is_array($specData)&&count($specData)>0){
                            $goods_spec = [];
                            foreach($specData as $k=>$v){
                                $sInfo = M('goods_spec_value')->where(['id'=>$v])->find();
                                $goods_spec[] = $sInfo['spec_title'];
                                $data['spec_type'] = $sInfo['tid'];
                            }
                    }
                    $val['goods_sku'] = 'S'.date('YmdHis',time()).rand(1000,9999);
                    $val['goods_title'] = $data['goods_title'];
                    $val['goods_spec'] = implode(',',$goods_spec);
                    $itemData[] = $val;
                    $goodsPrice[] = $val['selling_price'];
                }
			}else{//单规格
                $data['is_more_spec'] = 0;
                $itemData = [];
                $itemData[0]['goods_title'] = $data['goods_title'];
                $itemData[0]['goods_spec'] = '默认';
                $itemData[0]['market_price'] = $data['market_price'];
                $itemData[0]['selling_price'] = $data['selling_price'];
                $itemData[0]['retail_price'] = $data['retail_price'];
                $itemData[0]['goods_sku'] = 'S'.date('YmdHis',time()).rand(1000,9999);
                unset($data['market_price']);
                unset($data['selling_price']);
                unset($data['retail_price']);
                $goodsPrice[] = $data['selling_price'];
            }
			if(!empty($data['goods_content'])){
				$data['goods_content'] = stripslashes(htmlspecialchars_decode($data['goods_content']));
			}
			$data['addtime'] = date('Y-m-d H:i:s',time());
            $data['spec_type_id'] = empty($data['product_type'])?1:$data['product_type'];
            $data['bn'] = date('YmdHis').rand(1000,9999);
            $data['goods_price'] = min($goodsPrice);
			if($goods_id = D('Goods')->addGoods($data)){
                if(is_array($itemData)&&count($itemData)>0){
                    foreach($itemData as &$val){
                        $val['goods_id'] = $goods_id;
                        $val['addtime'] = date('Y-m-d H:i:s',time());
                        D('GoodsList')->addGoodsList($val);
                    }
                }
				$ret = array('code'=>1,'message'=>'添加成功');
				$this->ajaxReturn($ret);
			}else{
				$ret = array('code'=>0,'message'=>'添加失败!');
				$this->ajaxReturn($ret);
			}
		}else{
		    $type = I('type',3);
			$goodsCateList = D('GoodsCate')->getGoodsCateAllList(0,$type);
			if(is_array($goodsCateList)&&count($goodsCateList)>0){
				foreach($goodsCateList as &$val){
					$val['second_list'] = M('goods_cate')->where(['pid'=>$val['id'],'status'=>1,'is_deleted'=>0])->order('sort desc,id desc')->select();
				}
			}
            $brandList = D('GoodsBrand')->getGoodsBrandAllList();
            $this->assign('brandList',$brandList);
			$this->assign('goodsCateList',$goodsCateList);
			$this->display();
		}
	}
	
	/*
	* Function:		addGoods
	* Description:	添加商品
	*/
	public function addCard(){
	    $type = I('type',3);
		$goodsCateList = D('GoodsCate')->getGoodsCateAllList(0,$type);
		if(is_array($goodsCateList)&&count($goodsCateList)>0){
			foreach($goodsCateList as &$val){
				$val['second_list'] = M('goods_cate')->where(['pid'=>$val['id'],'status'=>1,'is_deleted'=>0])->order('sort desc,id desc')->select();
			}
		}
        $brandList = D('GoodsBrand')->getGoodsBrandAllList();
        $this->assign('brandList',$brandList);
		$this->assign('goodsCateList',$goodsCateList);
		$this->display();
	}
	
	/*
	* Function:		editGoods
	* Description:	编辑商品
	* @param:		$id int id
	*/
	public function editGoods($id = ''){
		if(IS_POST){
		    try{
		        D('Goods')->startTrans();
		        $data = I('post.');
    			if(is_array($data['smallimage'])&&count($data['smallimage'])>0){
    			    $data['goods_small_pic'] = $data['smallimage'][0];
    			    $data['goods_image'] = implode(',',$data['smallimage']);
    			}
    			unset($data['smallimage']);
    			if(empty($data['spec_type'])){
    			    unset($data['spec_type']);
    			}
                $goodsPrice = [];//多规格商品价格数组
                $goodsList = M('goods_list')->where(['goods_id'=>$data['id']])->select();
                //先删除规格
                if(!M('goods_list')->where(['goods_id'=>$data['id']])->delete()){
                    D('Goods')->rollback();
                    $ret = array('code'=>0,'message'=>'删除规格失败!');
                    $this->ajaxReturn($ret);
                }
                if(is_array($data['skus'])&&count($data['skus'])>0){//多规格
                    $itemData = [];
                    $data['is_more_spec'] = 1;
                    $yGoodsList = [];
                    if(is_array($goodsList)&&count($goodsList)>0){
                        foreach($goodsList as $key=>$val){
                            $yGoodsList[$val['goods_spec_id']] = $val;
                        }
                    }
                    foreach($data['skus'] as $key=>$val){
                        $val['goods_spec_id'] = $key;
                        $specData = explode('-',$key);
                        if(is_array($specData)&&count($specData)>0){
                            $goods_spec = [];
                            foreach($specData as $k=>$v){
                                $sInfo = M('goods_spec_value')->where(['id'=>$v])->find();
                                $goods_spec[] = $sInfo['spec_title'];
                                $data['spec_type'] = $sInfo['tid'];
                            }
                        }
                        $val['goods_sku'] = 'S'.date('YmdHis',time()).rand(1000,9999);
                        $val['goods_title'] = $data['goods_title'];
                        $val['goods_spec'] = implode(',',$goods_spec);
                        $val['stocks'] = isset($yGoodsList[$val['goods_spec_id']])?$yGoodsList[$val['goods_spec_id']]['stocks']:0;
                        $val['freez'] = isset($yGoodsList[$val['goods_spec_id']])?$yGoodsList[$val['goods_spec_id']]['freez']:0;
                        $itemData[] = $val;
                        $goodsPrice[] = $val['selling_price'];
                    }
                }else{//单规格
                    $yGoodsList = [];
                    if(is_array($goodsList)&&count($goodsList)>0){
                        foreach($goodsList as $key=>$val){
                            $yGoodsList[$val['goods_spec_id']] = $val;
                        }
                    }
                    $data['is_more_spec'] = 0;
                    $itemData = [];
                    $itemData[0]['goods_title'] = $data['goods_title'];
                    $itemData[0]['goods_spec'] = '默认';
                    $itemData[0]['market_price'] = $data['market_price'];
                    $itemData[0]['selling_price'] = $data['selling_price'];
                    $itemData[0]['retail_price'] = $data['retail_price'];
                    $itemData[0]['goods_sku'] = 'S'.date('YmdHis',time()).rand(1000,9999);
                    $itemData[0]['stocks'] = isset($goodsList[0])?$goodsList[0]['stocks']:0;
                    $itemData[0]['freez'] = isset($goodsList[0])?$goodsList[0]['freez']:0;
                    unset($data['market_price']);
                    unset($data['selling_price']);
                    unset($data['retail_price']);
                    $goodsPrice[] = $data['selling_price'];
                }
    			if(!empty($data['goods_content'])){
    				$data['goods_content'] = stripslashes(htmlspecialchars_decode($data['goods_content']));
    			}
                $data['spec_type_id'] = empty($data['product_type'])?1:$data['product_type'];
                $data['goods_price'] = min($goodsPrice);
    			$ret = D('Goods')->updateGoods($data);
    			if($ret!==false){
                    if(is_array($itemData)&&count($itemData)>0){
                       foreach($itemData as &$val){
                          $val['goods_id'] = $data['id'];
                          $val['addtime'] = date('Y-m-d H:i:s',time());
                          D('GoodsList')->addGoodsList($val);
                       }
                    }
                    D('Goods')->commit();
    				$ret = array('code'=>1,'message'=>'更新成功');
    				$this->ajaxReturn($ret);
    			}else{
    			    D('Goods')->rollback();
    				$ret = array('code'=>0,'message'=>'更新失败!');
    				$this->ajaxReturn($ret);
    			}
		    }catch(Exception $e){
		        D('Goods')->rollback();
		        $this->ajaxReturn(['code'=>0,'message'=>$e->getMessage()]);
		    }
		}else{
			if(empty($id)){
				$this->error('参数异常');
			}else{
				$info = D('Goods')->getGoodsInfo($id);
				$this->assign('info',$info);
				if(!empty($info['goods_image'])){
    				$imgUrlList = explode(',',trim($info['goods_image'],','));
    				$this->assign('imgUrlList',$imgUrlList);
    			}
    			$type = 3;
    			if($info['cate_id']==1){
    			    $type = 1;   
    			}else if($info['cate_id']==2){
    			    $type = 2;   
    			}
				$goodsCateList = D('GoodsCate')->getGoodsCateAllList(0,$type);
				if(is_array($goodsCateList)&&count($goodsCateList)>0){
					foreach($goodsCateList as &$val){
						$val['second_list'] = M('goods_cate')->where(['pid'=>$val['id'],'status'=>1,'is_deleted'=>0])->order('sort desc,id desc')->select();
					}
				}
				$this->assign('goodsCateList',$goodsCateList);
				$goodsList = D('GoodsList')->getGoodsListAllList($info['id']);
				$this->assign('goodsList',$goodsList);
                $brandList = D('GoodsBrand')->getGoodsBrandAllList();
                $this->assign('brandList',$brandList);
                if($info['cate_id']==1){
                    $this->display('editVideo');
                }else if($info['cate_id']==2){
                    $this->display('editCard');
                }else{
                   $this->display(); 
                }
			}
		}
	}

	/*
	* Function:		goodsCateList
	* Description:	商品分类列表
	*/
    public function goodsCateList(){
		$filter = I('param.');
		$page =  I('get.p',1);
		$pageSize = 100;
		$filter = returnFilter($filter);
		$list = D('GoodsCate')->getGoodsCateList($page,$filter,$pageSize);
		if(is_array($list)&&count($list)>0){
			foreach($list as &$val){
				$val['second_list'] = M('goods_cate')->where(['pid'=>$val['id'],'status'=>1,'is_deleted'=>0])->order('sort desc,id desc')->select();
				if($val['type']==1){
				    $val['type_name'] = '视频';
				}else if($val['type']==2){
				    $val['type_name'] = '会员卡';
				}else{
				    $val['type_name'] = '商品';
				}
			}
		}
		$count =  D('GoodsCate')->getGoodsCateCount($filter);
		$pages = getpage($count,$pageSize,$filter);
		$show = $pages->show();
		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->assign('filter',$filter);
		$this->display();
    }
	
	/*
	* Function:		addGoodsCate
	* Description:	添加商品分类
	*/
	public function addGoodsCate(){
		$ret = array();
		if(IS_POST){
			$data = I('post.');
			if(empty($data['pid'])){
			    $data['pid'] = 0;
			}
			$data['addtime'] = date('Y-m-d H:i:s',time());
			if(D('GoodsCate')->addGoodsCate($data)){
				$ret = array('code'=>1,'message'=>'添加成功');
				$this->ajaxReturn($ret);
			}else{
				$ret = array('code'=>0,'message'=>'添加失败!');
				$this->ajaxReturn($ret);
			}
		}else{
			$cateList = D('GoodsCate')->getGoodsCateAllList(0,3);
			$this->assign('cateList',$cateList);
			$typeList = [['id'=>1,'name'=>'视频'],['id'=>2,'name'=>'会员卡'],['id'=>3,'name'=>'商品']];
			$this->assign('typeList',$typeList);
			$this->display();
		}
	}
	
	/*
	* Function:		editGoodsCate
	* Description:	编辑快递
	* @param:		$id int id
	*/
	public function editGoodsCate($id = ''){
		if(IS_POST){
			$data = I('post.');
			if(empty($data['pid'])){
			    $data['pid'] = 0;
			}
			$ret = D('GoodsCate')->updateGoodsCate($data);
			if($ret!==false){
				$ret = array('code'=>1,'message'=>'更新成功');
				$this->ajaxReturn($ret);
			}else{
				$ret = array('code'=>0,'message'=>'更新失败!');
				$this->ajaxReturn($ret);
			}
		}else{
			if(empty($id)){
				$this->error('参数异常');
			}else{
				$info = D('GoodsCate')->getGoodsCateInfo($id);
				$this->assign('info',$info);
				if($info['pid']!=0){
					$cateList = D('GoodsCate')->getGoodsCateAllList(0,3);
					$this->assign('cateList',$cateList);
				}
				$typeList = [['id'=>1,'name'=>'视频'],['id'=>2,'name'=>'会员卡'],['id'=>3,'name'=>'商品']];
			    $this->assign('typeList',$typeList);
				$this->display();
			}
		}
	}
	
	/*
	* Function:		operatorRent
	* Description:	操作商品列表—上下架
	* @param:		$id int 商品id
	*/
	public function operatorGoods($id = '',$status = ''){
		if(!$info = D('Goods')->getGoodsInfo($id)){
			$ret = array('code'=>0,'message'=>'不存在此商品');
			$this->ajaxReturn($ret);
		}
		$data = array();
		$data['id'] = $id;
		$data['status'] = $status;
		if(D('Goods')->updateGoods($data)){
			$ret = array('code'=>1,'message'=>'操作成功');
			$this->ajaxReturn($ret);
		}else{
			$ret = array('code'=>0,'message'=>'操作失败!');
			$this->ajaxReturn($ret);
		}
	}
	
	/*
	* Function:		goodsCommentList
	* Description:	商品评论列表
	*/
    public function goodsCommentList(){
		$filter = I('param.');
		$page =  I('get.p',1);
		$pageSize = 10;
		$filter = returnFilter($filter);
		$filter['flag'] = 1;
		$list = D('OrderComment')->getOrderCommentList($page,$filter,$pageSize);
		if(is_array($list)&&count($list)>0){
		    foreach($list as &$val){
		        $gInfo = M('goods')->where(['id'=>$val['goods_id']])->find();
		        $gListInfo = M('goods_list')->where(['id'=>$val['goods_list_id']])->find();
		        $val['goods_name'] = $gInfo['goods_title'].'('.$gListInfo['goods_spec'].')';
		        $userInfo = M('user')->where(['id'=>$val['user_id']])->find();
		        $val['username'] = $userInfo['username'];
		    }
		}
		$count =  D('OrderComment')->getOrderCommentCount($filter);
		$pages = getpage($count,$pageSize,$filter);
		$show = $pages->show();
		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->assign('filter',$filter);
		$this->display();
    }
    
    /*
	* Function:		auitGoodsComment
	* Description:	商品评论审核
	*/
    public function auitGoodsComment($id = ''){
		if(IS_POST){
			$arr = array();
			$data = I('post.');
			if(!$info = M('order_comment')->where(['id'=>$data['id']])->find()){
			    $ret = array('code'=>0,'message'=>'不存在此评论!');
				$this->ajaxReturn($ret);
			}
			$data['reply_time'] = date('Y-m-d H:i:s',time());
			$data['op_id'] = session(C('USER_AUTH_KEY'));
			if($data['auitSelect']==1){
			    $data['status'] = 1;
			}else if($data['auitSelect']==2){
				$data['status'] = 2;
				if(empty($data['reason'])){
					$ret = array('code'=>0,'message'=>'审核不通过原因不能为空!');
					$this->ajaxReturn($ret);
				}
				$data['op_memo'] = $data['reason'];
			}
			$ret = M('order_comment')->where(['id'=>$data['id']])->save($data);
			if($ret!==false){
				$ret = array('code'=>1,'message'=>'提交成功!');
				$this->ajaxReturn($ret);
			}else{
				$ret = array('code'=>0,'message'=>'提交失败!');
				$this->ajaxReturn($ret);
			}
		}else{
			$info = M('order_comment')->where(['id'=>$id])->find();
			$gInfo = M('goods')->where(['id'=>$info['goods_id']])->find();
		    $gListInfo = M('goods_list')->where(['id'=>$info['goods_list_id']])->find();
		    $info['goods_title'] = $gInfo['goods_title'];
		    $info['goods_spec'] = $gListInfo['goods_spec'];
		    $info['goods_img_url'] = $gListInfo['goods_img_url'];
		    if($info['evaluate']==1){
		        $info['evaluate'] = '超赞';
		    }else if($info['evaluate']==2){
		        $info['evaluate'] = '满意';
		    }else{
		        $info['evaluate'] = '一般';
		    }
		    $imageList = explode(',',$info['images']);
			$this->assign('info',$info);
			$this->assign('id',$id);
			$this->assign('imageList',$imageList);
			$auitSelectList = array(array('value'=>1,'name'=>'通过'),array('value'=>2,'name'=>'不通过'));
			$this->assign('auitSelectList',$auitSelectList);
			$this->display();
		}
    }
    
    /*
	* Function:		updateGoodStocks
	* Description:	修改商品库存
	*/
    public function updateGoodStocks($id = ''){
        if(IS_POST){
			$arr = array();
			$goods_id = I('id','');
			$goods_list_id = I('goods_list_id','');
			$stocks = I('stocks',0);
			$logData = [];
			$logData['order_id'] = 'SD'.time();
			$logData['goods_id'] = $goods_id;
			$logData['type'] = 'putin';
			$logData['op_name'] = session('login_name');
			$logData['addtime'] = date('Y-m-d H:i:s',time());
			if(is_array($goods_list_id)&&count($goods_list_id)>0){
			    $total_stocks = 0;
			    //D('Goods')->startTrans();
			    foreach($goods_list_id as $key=>$val){
			        $goodsListInfo = M('goods_list')->where(['id'=>$val])->find();
			        $data = [];
			        if($stocks[$key]<0){
			            //D('Goods')->rollback();
			            $ret = array('code'=>0,'message'=>'库存不能为负数，请检查!');
					    $this->ajaxReturn($ret);
			        }
			        $total_stocks += $stocks[$key];
			        $data['stocks'] = $stocks[$key];
			        $ret = M('goods_list')->where(['id'=>$val])->save($data);
			        if($ret===false){
			            //D('Goods')->rollback();
			            $ret = array('code'=>0,'message'=>'更新失败!');
					    $this->ajaxReturn($ret);
			        }
			        if(($stocks[$key]-$goodsListInfo['stocks'])>0){
			            $logData['goods_list_id'] = $val;
    			        $logData['num'] = $stocks[$key]-$goodsListInfo['stocks'];
    			        M('storage_logs')->add($logData);
			        }
			    }
			    $ret = M('goods')->where(['id'=>$goods_id])->save(['stocks'=>$total_stocks]);
			    if($ret!==false){
			       // D('Goods')->commit();
    				$ret = array('code'=>1,'message'=>'更新成功!');
    				$this->ajaxReturn($ret);
    			}else{
    			   // D('Goods')->rollback();
    				$ret = array('code'=>0,'message'=>'更新失败!');
    				$this->ajaxReturn($ret);
    			}
			}else{
				$ret = array('code'=>0,'message'=>'不存在数据!');
				$this->ajaxReturn($ret);
			}
		}else{
		   $goodsInfo = M('goods')->where(['id'=>$id])->find();
			$goodsList = M('goods_list')->where(['goods_id'=>$id])->select();
			$this->assign('goodsInfo',$goodsInfo);
			$this->assign('goodsList',$goodsList);
			$this->display();
		}
   }

   /*
	* Function:		getGoodsSpecType
	* Description:	获取商品规格类型
	*/
	public function getGoodsSpecType(){
		$data = array();
      $list = M('goods_spec_type')->field('id,title')->where(['status'=>1,'is_deleted'=>0])->select();
      $data['code'] = 200;
      $data['data'] = $list;
      $data['msg'] = '获取成功';
		$this->ajaxReturn($data);
	}

   /*
	* Function:		getGoodsSpecValue
	* Description:	获取商品规格值
	*/
	public function getGoodsSpecValue(){
		$data = array();
      $product_type_id = I('product_type_id','');
      $goods_id = I('goods_id','');
      $data['data'] = [];
      $goodsSpecData = [];
      if(!empty($product_type_id)){
         $data['data']['attribute'] = [];
         $list = M('goods_spec')->where(['tid'=>$product_type_id,'status'=>1,'is_deleted'=>0])->select();
         if(!empty($goods_id)){
            $goodsList = M('goods_list')->where(['goods_id'=>$goods_id])->select();
            if(is_array($goodsList)&&count($goods_id)>0){
               foreach($goodsList as $key=>$val){
                  $tempData = explode('-',$val['goods_spec_id']);
                  foreach($tempData as $k=>$v){
                     if(!in_array($v,$goodsSpecData[$k])){
                        $goodsSpecData[$k][] = $v;
                     }
                  }
               }
            }
         }
         if(is_array($list)&&count($list)>0){
            $spec = [];
            foreach($list as $key=>$val){
               $spec[$key]['id'] = $val['id'];
               $spec[$key]['title'] = $val['spec_title'];
               if(count($goodsSpecData[$key])>0){
                  $spec[$key]['value'] = $goodsSpecData[$key];
               }else{
                  $spec[$key]['value'] = [];
               }
               $spec[$key]['options'] = [];
               $sList = M('goods_spec_value')->where(['oid'=>$val['id'],'status'=>1,'is_deleted'=>0])->select();
               if(is_array($sList)&&count($sList)>0){
                  foreach($sList as $k=>$v){
                     $spec[$key]['options'][$k]['id'] = $v['id'];
                     $spec[$key]['options'][$k]['title'] = $v['spec_title'];
                  }
               }
            }
            $data['data']['spec'] = $spec;
         }
      }
      $data['code'] = 200;
      $data['msg'] = '获取成功';
		$this->ajaxReturn($data);
	}

   /*
	* Function:		createGoodsSpec
	* Description:	创建商品规格
	*/
	public function createGoodsSpec(){
      $data = array();
      $title = I('title','');
      $tid = I('product_type_id','');
      $iData = [];
      $iData['tid'] = $tid;
      $iData['spec_title'] = $title;
      $iData['addtime'] = date('Y-m-d H:i:s',time());
      if(!$lastId = M('goods_spec')->add($iData)){
         $data['code'] = 0;
         $data['data'] = '';
         $data['msg'] = '创建规格失败';
      }else{
         $data['code'] = 200;
         $data['data']['id'] = $lastId;
         $data['msg'] = '创建规格成功';
      }
		$this->ajaxReturn($data);
	}

   /*
	* Function:		deleteGoodsSpec
	* Description:	删除商品规格
	*/
	public function deleteGoodsSpec(){
      $data = array();
      $id = I('id','');
      if(!M('goods_spec')->where(['id'=>$id])->delete()){
         $data['code'] = 0;
         $data['data'] = '';
         $data['msg'] = '删除规格失败';
      }else{
         $data['code'] = 200;
         $data['data'] = '';
         $data['msg'] = '删除规格成功';
      }
		$this->ajaxReturn($data);
	}

   /*
	* Function:		createGoodsSpecValue
	* Description:	创建商品规格值
	*/
	public function createGoodsSpecValue(){
      $data = array();
      $title = I('title','');
      $oid = I('spec_id','');
      if(!$info = M('goods_spec')->where(['id'=>$oid])->find()){
         $data['code'] = 0;
         $data['data'] = '';
         $data['msg'] = '不存在此规则名';
         $this->ajaxReturn($data);
      }
      $iData = [];
      $iData['tid'] = $info['id'];
      $iData['oid'] = $oid;
      $iData['spec_title'] = $title;
      $iData['addtime'] = date('Y-m-d H:i:s',time());
      if(!$lastId = M('goods_spec_value')->add($iData)){
         $data['code'] = 0;
         $data['data'] = '';
         $data['msg'] = '创建规格值失败';
      }else{
         $data['code'] = 200;
         $data['data']['id'] = $lastId;
         $data['msg'] = '创建规格值成功';
      }
		$this->ajaxReturn($data);
	}

   /*
	* Function:		deleteGoodsSpecValue
	* Description:	删除商品规格值
	*/
	public function deleteGoodsSpecValue(){
      $data = array();
      $id = I('id','');
      if(!M('goods_spec_value')->where(['id'=>$id])->delete()){
         $data['code'] = 0;
         $data['data'] = '';
         $data['msg'] = '删除规格值失败';
      }else{
         $data['code'] = 200;
         $data['data'] = '';
         $data['msg'] = '删除规格值成功';
      }
		$this->ajaxReturn($data);
	}

   /*
	* Function:		getGoodsSkuData
	* Description:	获取商品SKU数据
	*/
	public function getGoodsSkuData(){
		$data = array();
      $product_id = I('product_id','');
      if(empty($product_id)){
         $data['code'] = 0;
         $data['data'] = '';
         $data['msg'] = '缺少商品id参数';
         $this->ajaxReturn($data);
      }
      $goodsInfo = M('goods')->where(['id'=>$product_id])->find();
      $list = M('goods_list')->where(['goods_id'=>$product_id,'status'=>1,'is_deleted'=>0])->select();
      if(is_array($list)&&count($list)>0){
         $skus = [];
         if($goodsInfo['is_more_spec']==1){
            foreach($list as $key=>$val){
               $skus["skus[".$val['goods_spec_id']."][goods_img_url]"] = $val['goods_img_url'];
               $skus["skus[".$val['goods_spec_id']."][selling_price]"] = $val['selling_price'];
               $skus["skus[".$val['goods_spec_id']."][market_price]"] = $val['market_price'];
               $skus["skus[".$val['goods_spec_id']."][retail_price]"] = $val['retail_price'];
               $skus["skus[".$val['goods_spec_id']."][stock]"] = "0";
               $skus["skus[".$val['goods_spec_id']."][status]"] = $val['status'];
            }
         }else{
            foreach($list as $key=>$val){
               $skus['selling_price'] = $val['selling_price'];
               $skus['market_price'] = $val['market_price'];
               $skus['retail_price'] = $val['retail_price'];
               $skus['status'] = $val['status'];
            }
         }
         $data['data'] = $skus;
      }
      $data['code'] = 200;
      $data['msg'] = '获取sku数据成功！';
		$this->ajaxReturn($data);
	}

   /*
	* Function: importProduct
	* description:商品导入
	*/
	public function importProduct(){
		if(IS_POST){
			//设置编码防止乱码
			header("Content-Type:text/html;charset=utf-8");
			$filter = I('post.');
			$upload = new \Think\Upload();// 实例化上传类
			$upload->maxSize   =	3145728 ;// 设置附件上传大小
			$upload->exts      =	array('xls','xlsx');// 设置附件上传类
			$upload->savePath  =	'/'; // 设置附件上传目录
			$upload->replace   =	true; //存在同名文件是否是覆盖，默认为false
			//上传文件
			$info = $upload->uploadOne($_FILES['file']);
			$filename = './Uploads'.$info['savepath'].$info['savename'];
			$exts = $info['ext'];
			if(!$info) {// 上传错误提示错误信息
				$this->error($upload->getError());
			}else{//上传成功
				$data = importExcel($filename,$exts);
				D('Goods')->startTrans();
				if($result = D('Goods')->importProduct($data,$filter)){
					D('Goods')->commit();
					$this->assign('success',$result);
				}else{
					D('Goods')->rollback();
					$this->assign('error',D('Goods')->get_error());
				}
			}          
		}
		$this->display();
	}
	
	/*
	* Function:		goodsBrandList
	* Description:	商品品牌列表
	*/
    public function goodsBrandList(){
		$filter = I('param.');
		$page =  I('get.p',1);
		$pageSize = 10;
		$filter = returnFilter($filter);
		$list = D('GoodsBrand')->getGoodsBrandList($page,$filter,$pageSize);
		$count =  D('GoodsBrand')->getGoodsBrandCount($filter);
		$pages = getpage($count,$pageSize,$filter);
		$show = $pages->show();
		$this->assign('list',$list);
		$this->assign('page',$show);
		$this->assign('filter',$filter);
		$this->display();
    }
	
	/*
	* Function:		addGoodsBrand
	* Description:	添加商品品牌
	*/
	public function addGoodsBrand(){
		$ret = array();
		if(IS_POST){
			$data = I('post.');
			$data['addtime'] = date('Y-m-d H:i:s',time());
			if(D('GoodsBrand')->addGoodsBrand($data)){
				$ret = array('code'=>1,'message'=>'添加成功');
				$this->ajaxReturn($ret);
			}else{
				$ret = array('code'=>0,'message'=>'添加失败!');
				$this->ajaxReturn($ret);
			}
		}else{
			$brandList = D('GoodsBrand')->getGoodsBrandAllList(0);
			$this->assign('brandList',$brandList);
			$this->display();
		}
	}
	
	/*
	* Function:		editGoodsBrand
	* Description:	编辑品牌
	* @param:		$id int id
	*/
	public function editGoodsBrand($id = ''){
		if(IS_POST){
			$data = I('post.');
			$ret = D('GoodsBrand')->updateGoodsBrand($data);
			if($ret!==false){
				$ret = array('code'=>1,'message'=>'更新成功');
				$this->ajaxReturn($ret);
			}else{
				$ret = array('code'=>0,'message'=>'更新失败!');
				$this->ajaxReturn($ret);
			}
		}else{
			if(empty($id)){
				$this->error('参数异常');
			}else{
				$info = D('GoodsBrand')->getGoodsBrandInfo($id);
				$this->assign('info',$info);
				$this->display();
			}
		}
	}
}